package com.baozun.dev.payment.alipay;


import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.baozun.dev.data.AliPayData;
import com.baozun.dev.payment.Payment;

import java.util.Map;

/**
 * Created by joker.wang on 2017/8/15.
 */

public class AliPayPayment implements Payment {
    public static final int SDK_PAY_FLAG = 100;


    private static final String RSA2_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJi5XkiQ8R0u/6IwiS1UdaVJDE7Lmja3Pf2H1vrbACpBCrXeP7Irp3RtQtkRDmw5aZnDI3yoenXvqnBzdWYB0auLVmUvGjbbaWdBoevIBRa5CPUwLd08oH8CErOKKPshoT1zOxvl3dfV5xfmrkH68WO38R8U7SuoHZXRZckPT/iRAgMBAAECgYEAjTzgtLtWQGb2gkfglMtHAVRMzZH9TByqd4zog5WE0Y7VGNwwi9VTR5jD+XqMnAl8X3bXmrE0j1zVgqlEKNIF0+kbnWlANeu/3J+JTJjfJq8AcJEPXIsmr0Y67G+Bib1IFPVyq3E3+WuPw6w3GL8C720gNdBeAsgmnMzGJFs3VwECQQD1DI2SycCU70/wA5S5lJ0bO5H1wsyJkEIMs+h6I9uRcMdlQh40SbCA7v95J9C6ZiG5/Dkk5r4NTZrOH0ATsoKTAkEAn4yV5od6JP/eJapRgWn9NMACG1S0rRpDhuYDYbwp1zXKaDrP21RyVTNeMHQKB2NS0dPFSwqsKNRrhbIwLLKaywJACBdmBVbMGR7d0NsNaiNSHLgW1bqc7l3pEGpQXtgYQ/EpZFqOjMNyJI+/t8xsw/rjWjTN3j4QQHgziGLXxs66KQJAEL3y2N7sfUdwKymlJdxWWpuvXOjVkLiJz3UBc9cH2PJnC+rn9s70tGYQgysaBk5w2V3MfSRgjmRD6CKblYUkYwJANUeHDgZUZQNS6pY6fLpwprgDHJkzbXd/zQ6DUxqo9g3+HwmpOUpYmYpzk5WtZjCfnGZ2cXcQJC6vUo8dk+Nsww==";
    private static final String APPID = "2016082000296319";

    Handler aliPayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 支付宝支付回调
                case SDK_PAY_FLAG:
                    Result resultObj = new Result((String) msg.obj);
                    String resultStatus = resultObj.resultStatus;

                    boolean hasNoPay = !TextUtils.equals(resultStatus, "9000");
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(context,"支付成功",Toast.LENGTH_SHORT).show();
//                        getPaySuccess();
                    } else if("6001".equals(resultStatus)){
                        Toast.makeText(context,"用户中途取消",Toast.LENGTH_SHORT).show();
                        // if (payinfo.type == 0) {
                        // UIHelper.toOrderActivity(context, Constants.TYPE_WAITPAY,
                        // null);
                        // }
                        // if (context instanceof OrderNewActivity)
                        // {//如果是购物车页面跳转过来的才进行跳转
                        // UIHelper.toOrderActivity(context,
                        // Constants.TYPE_WAITPAY,null);
                        // }
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”
                        // 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        // if (TextUtils.equals(resultStatus, "8000")) {
                        // Toast.makeText(context, "支付结果确认中", Toast.LENGTH_SHORT)
                        // .show();
                        // } else {
                        // Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT)
                        // .show();
                        // }
                    }else{
                        Toast.makeText(context,"支付失败",Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    };



    private Context context;

    private AliPayData payinfo;

    public AliPayPayment(Context context, AliPayData payinfo) {
        this.context = context;
        this.payinfo = payinfo;
    }

    @Override
    public void payment() {
        aliPayPayment();
    }

    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    private void aliPayPayment() {
// String info = getNewOrderInfo();
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = RSA2_PRIVATE ;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;
        Log.i("ExternalPartner", "start pay");
// start the pay.
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask((Activity) context);
                // 调用支付接口
                String result = alipay.pay(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                aliPayHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

}
